// src/stores/modules/app.js
import { defineStore } from 'pinia';
import { Login } from '@/api/account';

export const useAppStore = defineStore('app', {
  state: () => ({
    token: '',
    username: '',
    role: '',
    collapse: false
  }),
  getters: {},
  actions: {
    toggleCollapseAction() {
      this.collapse = !this.collapse;
    },
    loginAction(requestData) {
      return new Promise((resolve, reject) => {
        Login(requestData)
          .then((response) => {
            const { token, username, role } = response.data;
            this.updateToken(token);
            this.updateUsername(username);
            this.updateUserRole(role);
            console.log('Logged in with role:', role); // 添加调试日志
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 更新 token 信息
    updateToken(token) {
      this.token = token;
    },
    updateUsername(username) {
      this.username = username;
    },
    updateUserRole(role) {
      this.role = role;
    },
    // 如果需要登出功能，可以添加以下方法
    // logoutAction() {
    //   return new Promise((resolve, reject) => {
    //     Logout()
    //       .then((response) => {
    //         this.updateToken('');
    //         this.updateUsername('');
    //         this.updateUserRole('');
    //         resolve(response);
    //       })
    //       .catch((error) => {
    //         reject(error);
    //       });
    //   });
    // }
  },
  persist: {
    storage: sessionStorage,
    key: 'pinia.app'
  }
});